﻿#include "filetrans_socket.h"
#include "mypdu.h"
#include "filetrans_server.h"
#include "filethread.h"



FileTrans_Socket::FileTrans_Socket()
{
    connect(this,&FileTrans_Socket::readyRead,this,&FileTrans_Socket::Recv);
    m_control = false;
    m_recvName = false;
    m_recvsize = 0;
}

FileTrans_Socket &FileTrans_Socket::getInstance()
{
    static FileTrans_Socket fs;
    return fs;
}


void FileTrans_Socket::Recv()
{
    QByteArray ba = readAll();
    if(!m_recvName)
    {
        QString str(ba);
        strcpy(m_u.pwd,str.toStdString().c_str());//接收登录名
        m_recvName = true;
        return;
    }
    if(!m_control)
    {
        QString str(ba);
        QString uname = str.section('&',0,0);
        QString upwd = str.section('&',1,1);
        m_filename = str.section('&',2,2);
        m_filesize = str.section('&',3,3).toUInt();
        strcpy(m_u.name,uname.toStdString().c_str());//接收 文件接收方
        QString file = QString("C:/Users/Administrator/Desktop/%1").arg(m_filename);
        m_file.setFileName(file);
        if(!m_file.open(QIODevice::WriteOnly))
        {
            qDebug()<<"create file fail"<<endl;
        }
        m_control = true;
    }
    else
    {
        int r = m_file.write(ba);
        m_recvsize += r;
        if(m_recvsize>=m_filesize)
        {
            m_control = false;
            m_recvsize = 0;
            m_file.close();
            QString filepath = QString("C:/Users/Administrator/Desktop/%1").arg(m_filename);

            FileTrans::getInstance().TransFileData(m_u.name,filepath,m_filename,m_filesize);
        }
    }

}
